package com.future.mayi.fragment;

import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.future.baselib.entity.BaseResponse;
import com.future.baselib.entity.DefaultResponse;
import com.future.baselib.utils.ApiCst;
import com.future.baselib.utils.CommonUtils;
import com.future.baselib.utils.HttpRequest;
import com.future.baselib.utils.LogUtils;
import com.future.baselib.view.LoadingDialog;
import com.future.mayi.R;
import com.future.mayi.activity.BaseFragment;
import com.future.mayi.activity.MainActivity;
import com.future.mayi.activity.NewGoodsOrderActivity;
import com.future.mayi.app.App;
import com.future.mayi.qsale.activity.CartActivity;
import com.future.mayi.qsale.adapter.CartGoodsAdapter;
import com.future.mayi.qsale.model.CartListModel;
import com.future.mayi.qsale.response.CartListResponse;
import com.future.mayi.utils.Arith;
import com.future.mayi.utils.HCUtils;
import com.future.mayi.utils.Navigator;
import com.future.mayi.utils.PriceUtils;
import com.future.mayi.view.xrecyclerview.XRecyclerView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

public class CartFragment extends BaseFragment implements XRecyclerView.LoadingListener, CartGoodsAdapter.OnCountChangeListener {

    @BindView(R.id.view_bar)
    View viewBar;
    @BindView(R.id.iv_title_left)
    ImageView ivTitleLeft;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_title_right)
    TextView tvTitleRight;
    @BindView(R.id.rl_main_title)
    RelativeLayout rlMainTitle;
    @BindView(R.id.view_main_line)
    View viewMainLine;
    @BindView(R.id.iv_empty_cart)
    ImageView ivEmptyCart;
    @BindView(R.id.tv_empty_hint)
    TextView tvEmptyHint;
    @BindView(R.id.rl_empty)
    RelativeLayout rlEmpty;
    @BindView(R.id.recycler_view)
    XRecyclerView recyclerView;
    @BindView(R.id.cb_all)
    CheckBox cbAll;
    @BindView(R.id.tv_confirm)
    TextView tvConfirm;
    @BindView(R.id.ll_bottom_bar)
    LinearLayout llBottomBar;
    @BindView(R.id.tv_price)
    TextView tvPrice;
    @BindView(R.id.tv_select_product)
    TextView tvSelectProduct;
    @BindView(R.id.ll_price)
    View llPrice;

    private CartGoodsAdapter adapter;
    private LoadingDialog mLoadingDialog;

    @Override
    protected int getLayoutResource() {
        return R.layout.fragment_cart;
    }

    @Override
    protected void initView() {
        if (MainActivity.statusBar) {
            ViewGroup.LayoutParams layoutParams = viewBar.getLayoutParams();
            layoutParams.height = CommonUtils.getStatusBarHeight(getActivity());
        } else viewBar.setVisibility(View.GONE);

        recyclerView.setHasFixedSize(true);
        final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
        recyclerView.setLayoutManager(linearLayoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        adapter = new CartGoodsAdapter(getContext(), null);
        adapter.setOnCountChangeListener(this);
        recyclerView.setAdapter(adapter);
        recyclerView.setLoadingListener(this);
        recyclerView.setLoadingMoreEnabled(false);
        cbAll.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (!isChecked && (System.currentTimeMillis() - cbAllUnSelectedTime) < 500) {
                    return;
                }
                adapter.selectAll(isChecked);
            }
        });

        tvTitleRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (adapter.isCountType()) {
                    tvTitleRight.setText("取消");
                    tvConfirm.setText("删除");
                    adapter.setIsCountType(false);
                    llPrice.setVisibility(View.INVISIBLE);
                } else {
                    tvTitleRight.setText("编辑");
                    tvConfirm.setText("结算");
                    adapter.setIsCountType(true);
                    llPrice.setVisibility(View.VISIBLE);
                }
            }
        });

        if (getActivity() instanceof CartActivity) {
            ivTitleLeft.setVisibility(View.VISIBLE);
        }

    }

    @Override
    protected void initListener() {
        tvConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (adapter.isCountType()) {
                    // TODO: 2018/8/21 结算
                    List<CartListModel> cartList = new ArrayList<>();
                    for (int i = 0; i < adapter.getList().size(); i++) {
                        if (adapter.getList().get(i).isSettleSelect()) {
                            cartList.add(adapter.getList().get(i));
                        }
                    }
                    if (cartList.size() <= 0) {
                        toast("请先选择商品!");
                        return;
                    }
                    NewGoodsOrderActivity.startActivity(getContext(), cartList);

                } else {
                    //删除
                    List<CartListModel> cartListModels = adapter.getList();
                    if (cartListModels == null || cartListModels.size() == 0) return;
                    List<Integer> cartId = new ArrayList<>();
                    for (int i = 0; i < cartListModels.size(); i++) {
                        if (cartListModels.get(i).isDeleteSelect()) {
                            cartId.add(cartListModels.get(i).getCart_id());
                        }
                    }
                    deleteCartGoods(cartId);
                }
            }
        });

        tvSelectProduct.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                LogUtils.d(TAG, "onClick");
                Navigator.navigatorGetLuxury(getContext());
            }
        });

        ivTitleLeft.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getActivity().finish();
            }
        });

    }

    @Override
    protected void initData() {
        getCartGoods();
    }

    public void deleteCartGoods(List<Integer> deleteList) {
        if (deleteList == null || deleteList.size() == 0) return;
        StringBuilder cartId = new StringBuilder();
        for (int i = 0; i < deleteList.size(); i++) {
            cartId.append(deleteList.get(i)).append(",");
        }
        String carIdString = cartId.substring(0, cartId.length() - 1);

        showLoadingDialog();
        new HttpRequest<DefaultResponse>()
                .with(getActivity())
                .setApiCode(ApiCst.delCart)
                .addParam("token", App.getToken(mContext))
                .addParam("cart_id", carIdString)
                .setListener(new HttpRequest.OnNetworkListener() {
                    @Override
                    public void onSuccess(BaseResponse response) {
                        dismissLoadingDialog();
                        successDeleteCart();
                    }

                    @Override
                    public void onFail(String message, BaseResponse response) {
                        dismissLoadingDialog();
                        HCUtils.loadFail(getContext(), message);
                    }
                })
                .start(new DefaultResponse());
    }

    private void dismissLoadingDialog() {
        if (mLoadingDialog == null) return;
        mLoadingDialog.close();
    }

    private void showLoadingDialog() {
        if (mLoadingDialog == null) {
            mLoadingDialog = new LoadingDialog(getActivity());
        }
        mLoadingDialog.show();
    }

    private void successDeleteCart() {
        if (adapter == null) return;
        List<CartListModel> cartListModels = adapter.getList();

        for (int i = cartListModels.size() - 1; i >= 0; i--) {
            if (cartListModels.get(i).isDeleteSelect()) {
                adapter.getList().remove(i);
            }
        }
        adapter.notifyDataSetChanged();

        if (adapter.getList() != null && adapter.getList().size() > 0) {
            rlEmpty.setVisibility(View.GONE);
            recyclerView.setVisibility(View.VISIBLE);
            visibleOption();
        } else {
            rlEmpty.setVisibility(View.VISIBLE);
            recyclerView.setVisibility(View.GONE);
            inVisibleOption();
        }

        tvPrice.setText(getFormatPrice(countPrice()));
    }

    private void getCartGoods() {
        if (!App.isLogin()) return;
        new HttpRequest<CartListResponse>()
                .with(getActivity())
                .setApiCode(ApiCst.getCartList)
                .addParam("token", App.getToken(mContext))
                .setListener(new HttpRequest.OnNetworkListener<CartListResponse>() {
                    @Override
                    public void onSuccess(CartListResponse response) {
                        HCUtils.refreshListForPage(recyclerView, adapter, response.getCartList(), 0, 10);
                        tvPrice.setText(getFormatPrice(countPrice()));
                        if (adapter.getList() != null && adapter.getList().size() > 0) {
                            rlEmpty.setVisibility(View.GONE);
                            recyclerView.setVisibility(View.VISIBLE);
                            visibleOption();
                        } else {
                            rlEmpty.setVisibility(View.VISIBLE);
                            recyclerView.setVisibility(View.GONE);
                            inVisibleOption();
                        }
                    }

                    @Override
                    public void onFail(String message, CartListResponse response) {
                        HCUtils.refreshFail(recyclerView, 1, getContext(), message);
                    }
                }).start(new CartListResponse());

    }


    public void showFragment() {
        onRefresh();
    }

    public void refresh() {
        onRefresh();
    }

    @Override
    public void onRefresh() {
        getCartGoods();
    }

    @Override
    public void onLoadMore() {
        recyclerView.loadMoreComplete();
        recyclerView.setNoMore(true);
    }

    private static final String TAG = "CartFragment";
    private double cbAllUnSelectedTime = 0;

    @Override
    public void onCountChange(int position, boolean isChecked) {
        tvPrice.setText(getFormatPrice(countPrice()));
        if (!isChecked && cbAll.isChecked()) {
            cbAllUnSelectedTime = System.currentTimeMillis();
            cbAll.setChecked(false);
        }
    }

    @Override
    public void onCheckedChange() {
        boolean selectAll = true;
        if (adapter.isCountType()) {
            for (int i = 0; i < adapter.getList().size(); i++) {
                if (!adapter.getList().get(i).isSettleSelect()) {
                    selectAll = false;
                }
            }
        } else {
            for (int i = 0; i < adapter.getList().size(); i++) {
                if (!adapter.getList().get(i).isDeleteSelect()) {
                    selectAll = false;
                }
            }
        }
        if (selectAll) {
            cbAll.setChecked(true);
        }

        if (adapter.isCountType()) {
            for (int i = 0; i < adapter.getList().size(); i++) {
                if (adapter.getList().get(i).isSettleSelect()) {
                    enableSubmitBtn();
                    return;
                }
            }
            disableSubmitBtn();
        } else {
            for (int i = 0; i < adapter.getList().size(); i++) {
                if (adapter.getList().get(i).isDeleteSelect()) {
                    enableSubmitBtn();
                    return;
                }
            }
            disableSubmitBtn();
        }

    }

    private void visibleOption() {
        if (llBottomBar.getVisibility() != View.VISIBLE) {
            llBottomBar.setVisibility(View.VISIBLE);
        }
        if (tvTitleRight.getVisibility() != View.VISIBLE) {
            tvTitleRight.setVisibility(View.VISIBLE);
        }
    }

    private void inVisibleOption() {
        if (llBottomBar.getVisibility() == View.VISIBLE) {
            llBottomBar.setVisibility(View.INVISIBLE);
        }
        if (tvTitleRight.getVisibility() == View.VISIBLE) {
            tvTitleRight.setVisibility(View.INVISIBLE);
        }
    }

    private void enableSubmitBtn() {
        tvConfirm.setEnabled(true);
        tvConfirm.setBackgroundResource(R.drawable.bg_cart_main);
    }

    private void disableSubmitBtn() {
        tvConfirm.setEnabled(false);
        tvConfirm.setBackgroundResource(R.drawable.bg_cart_gray);
    }

    private double countPrice() {
        List<CartListModel> cartGoodsModels = adapter.getList();
        double countPrice = 0;
        if (cartGoodsModels == null || cartGoodsModels.size() == 0) return 0;
        for (int i = 0; i < cartGoodsModels.size(); i++) {
            if (cartGoodsModels.get(i).isSettleSelect()) {
                countPrice = Arith.add(countPrice, cartGoodsModels.get(i).getGoods_price());
            }
        }
        return countPrice;
    }

    private String getFormatPrice(double price) {
        return String.valueOf(PriceUtils.getPriceText2(price));
    }
}
